from odoo import fields, models, api


class PurchaseMrpBom(models.Model):
    _inherit = 'mrp.bom.line'
    total_qty = fields.Float('零件需求总数')


class PurchaseOrder(models.Model):
    _inherit = 'purchase.order'
    purchase_bom = fields.Many2one('purchase.bom', 'Purchase Bom', ondelete='restrict')


    @api.multi
    def bwe_bom(self):
        name = self.name
        purchase_bom = name + 'S'
        bom_line_env = self.env['mrp.bom.line']
        pur_bom_line = self.env['purchase.bom.line'].sudo()
        purchase_env = self.env['purchase.order'].sudo()
        purchase_bom_e = self.env['purchase.bom'].sudo()
        purchase_order = purchase_env.search([('name', '=', name)])
        bom = {
            'name': purchase_bom,
            'partner_id': purchase_order.partner_id.id,
            'date_order': purchase_order.date_order,

        }
        pur_bom_ids = purchase_bom_e.search([('name', '=', purchase_bom)]).ids  # 零件订单编号
        if not pur_bom_ids:
            purchase_bom_e.create(bom)
            purchase_env.create(bom)
        print('32行',pur_bom_ids)
        print('33行',pur_bom_ids)
        date_planned = purchase_order.date_planned
        order_lines = purchase_order.order_line.ids
        print(order_lines)
        bom_lines = []  # 产品BOM线 获取这编号才能获取对应的零件,为零件生成新订单.
        product_id = []  # 产品的ID
        bom_p_id = []

        for order_line in order_lines:
            ll = purchase_order.order_line.browse(order_line).product_id.id
            pu_qty = purchase_env.order_line.browse(order_line).product_qty  # 产品数量 后面计算零件总数需要
            bom_products = purchase_env.order_line.browse(order_line).product_id.bom_ids.bom_line_ids.ids
            product_id.append(ll)  # 产品ID
            try:
                for i in bom_products:
                    bom_lines.append(i)
                    bom_qty = bom_line_env.browse(i).product_qty  # 产品零件个数
                    tot_qty = bom_qty * pu_qty
                    bom_line_env.browse(i).total_qty = tot_qty  # 产品需求零件总数
                    bom_product_id = bom_line_env.browse(i).product_id.id  # 零件的product_id,需要填入bom.
                    bom_p_id.append(bom_product_id)
                    print('零件ID:', bom_product_id, '零件名字:', bom_line_env.browse(i).product_id.name, '零件总数:',
                          bom_line_env.browse(i).total_qty,'零件价格:',bom_line_env.browse(i).product_id.lst_price)
            except Exception as e:
                pass
        bom = bom_line_env.browse(bom_lines)
        self.message_post_with_view('bom.bom_purchase_message_template',
                                    values={'bom_list': bom, 'purchase_order': purchase_order})
        try:
            for bl in bom_lines:
                order_bname = self.name + 'S'
                product_id = bom_line_env.browse(bl).product_id.id
                tot_qty = bom_line_env.browse(bl).total_qty
                order_id = purchase_bom_e.search([('name', '=', order_bname)]).id
                bom_name = bom_line_env.browse(bl).product_id.name
                val = {
                    'name': bom_name,
                    'product_qty': tot_qty,
                    'date_planned': date_planned,
                    'product_uom': 1,
                    'product_id': product_id,
                    'price_unit': bom_line_env.browse(bl).product_id.lst_price,
                    'order_id': order_id
                }
            # 去重,bom_name是零件名字加订单号,一个订单有且只有一种零件.
                pur_bom_line.create(val)  # 创建数据
        except Exception as e:

            print(e)
        s_u_m = 0
        try:
            for bi in bom_lines:
                order_bname = self.name + 'S'
                bom_name = bom_line_env.browse(bi).product_id.name
                order_id = purchase_bom_e.search([('name', '=', order_bname)]).id
                bom_l_ines = pur_bom_line.search(['&', ('name', '=', bom_name), ('order_id', '=', order_id)]).ids
                finish = pur_bom_line.search(['&', ('name', '=', bom_name+'零件'), ('order_id', '=', order_id)]).ids
                for f in finish:
                    pur_bom_line.browse(f).unlink()
                print(bom_name, '参考', bom_l_ines)
                order_id2 = pur_bom_line.browse(bom_l_ines[0]).order_id.id
                product_id2 = pur_bom_line.browse(bom_l_ines[0]).product_id.id
                price_unit = pur_bom_line.browse(bom_l_ines[0]).product_id.lst_price
                for bli in bom_l_ines:  # 两次
                    s_u_m += pur_bom_line.browse(bli).product_qty

                print(s_u_m)
                val2 = {
                    'name': bom_name+'零件',
                    'product_qty': s_u_m,
                    'date_planned': date_planned,
                    'product_uom': 1,
                    'product_id': product_id2,
                    'price_unit': price_unit,
                    'order_id': order_id2
                }
                print(val2)
                if bom_name:
                    pur_bom_line.create(val2)
                s_u_m = 0

            for ll in bom_lines:
                order_bname = self.name + 'S'
                bom_name = bom_line_env.browse(ll).product_id.name
                order_id = purchase_bom_e.search([('name', '=', order_bname)]).id
                bom_l_ines = pur_bom_line.search(['&', ('name', '=', bom_name), ('order_id', '=', order_id)]).ids
                for bl in bom_l_ines:
                    pur_bom_line.browse(bl).unlink()
        except Exception as e:

            print(e)


class PurchaseBom(models.Model):
    _name = 'purchase.bom'
    _inherit = 'purchase.order'

    order_line = fields.One2many('purchase.bom.line', 'order_id', string='Order Lines', states={'cancel': [('readonly', True)], 'done': [('readonly', True)]}, copy=True)
    purchase_order = fields.One2many('purchase.order', 'purchase_bom', string='询价单')


class PurchaseOrderLie(models.Model):
    _name = 'purchase.bom.line'
    _inherit = 'purchase.order.line'

    order_id = fields.Many2one('purchase.bom', string='Order Reference', index=True, required=True, ondelete='cascade')